<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 提示文本区域 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条区域 -->
      <el-steps align-center :active="activeIndex - 0" :space="200">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 添加信息区域 -->
      <el-form
        label-position="top"
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px">
        <!-- 侧边面板页签 -->
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="tabLeaveBefore"
          @tab-click="tabClick">
          <!-- 基本信息面板 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number" step="1" min="0"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number" step="1" min="0"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number" step="1" min="0"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联选择器区域 -->
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cascaderProps"
                @change="handleChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数面板 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyParamsList"
              :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="cbItem"
                  v-for="(cbItem, i) in item.attr_vals"
                  :key="i"
                  size="mini"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性面板 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyParamsList"
              :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片面板 -->
          <el-tab-pane label="商品图片" name="3">
            <!-- 注意：这里上传并没有用本项目配置的axios请求 -->
            <!-- 用的是组件内部封装的ajax，因此需要在请求头带上有效token -->
            <el-upload
              list-type="picture-card"
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="headersObj"
              :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品按钮 -->
            <el-button type="primary" class="addBtn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" :visible.sync="picDialogVisible" width="40%">
      <img :src="prevPicURL" alt="" class="prevPic" />
    </el-dialog>
  </div>
</template>

<script>
// 引入 lodash 插件
import _ from 'lodash'
export default {
  data() {
    return {
      // 当前步骤
      activeIndex: 0,
      // 添加商品表单信息
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        // 级联选择器选中ID数组
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 添加商品表单校验规则
      addFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }]
      },
      // 商品分类列表数据
      cateList: [],
      // 级联选择器配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 动态参数列表数据
      manyParamsList: [],
      // 动态属性列表数据
      onlyParamsList: [],
      // 查询动态参数或静态属性放查询条件 many 或 only
      sel: '',
      // 图片上传路径
      uploadURL: 'http://175.178.123.174:8888/api/private/v1/upload',
      // 上传文件组件的ajax请求头对象
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 控制图片预览对话框显示隐藏
      picDialogVisible: false,
      // 图片预览地址
      prevPicURL: ''
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    // 计算级联选择器选择的第三级分类ID
    cat_Id() {
      if (this.addForm.goods_cat.length !== 3) return null
      return this.addForm.goods_cat[2]
    }
  },
  methods: {
    // 获取商品分类列表数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.cateList = res.data
    },
    // 级联选择器发生改变时触发
    handleChange() {
      // console.log(this.addForm.goods_cat)
    },
    // 当页签野离开前触发
    tabLeaveBefore(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类！')
        return false
      }
    },
    // 获取动态参数或静态属性的请求
    async getParams() {
      const { data: res } = await this.$http.get(`categories/${this.cat_Id}/attributes`, {
        params: { sel: this.sel }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      return res.data
    },
    // 点击侧边页签触发函数
    async tabClick() {
      // 当点击商品参数页签
      if (this.activeIndex === '1') {
        this.sel = 'many'
        this.manyParamsList = await this.getParams()
        this.manyParamsList.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
        })
        // console.log(this.manyParamsList)
      } else if (this.activeIndex === '2') {
        this.sel = 'only'
        this.onlyParamsList = await this.getParams()
        // console.log(this.onlyParamsList)
      }
    },
    // 图片上传成功后的处理函数
    handleSuccess(response) {
      // console.log(response)
      const picsInfo = {
        pic: response.data.tmp_path
      }
      this.addForm.pics.push(picsInfo)
    },
    // 预览上传图片
    handlePreview(file) {
      // console.log(file.response.data.url)
      this.prevPicURL = file.response.data.url
      this.picDialogVisible = true
    },
    // 移除上传图片
    handleRemove(file) {
      const filePath = file.response.data.tmp_path
      this.addForm.pics = this.addForm.pics.filter(item => {
        return item.pic === filePath
      })
      // console.log(this.addForm)
    },
    // 添加商品
    addGoods() {
      // 表单校验
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写完成必要内容再添加！')
        }
        // 业务逻辑
        // 1. 处理动态参数
        this.manyParamsList.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals.join('') }
          this.addForm.attrs.push(newInfo)
        })
        // 2. 处理静态属性
        this.onlyParamsList.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.addForm.attrs.push(newInfo)
        })
        // 3. 双向数据绑定的数据处理
        //    先lodash.cloneDeep() 深拷贝，再将 goods_cat 数组拼接字符串
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        // 发起添加商品请求
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        // console.log(res)
        this.$message.success(res.meta.msg)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 15px 0;
}
.el-checkbox {
  margin: 0 5px 0 0 !important;
}

.prevPic {
  width: 100%;
}

.addBtn {
  margin-top: 5px;
}
</style>
